package com.mald.plugin.form;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.DocumentAdapter;
import com.mald.plugin.data.DataCenter;
import com.mald.plugin.data.DataProcessor;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class SearchForm {
    private JPanel contentPanel;
    private JTextField searchText;
    private JScrollPane scrollPane;
    private JTable searchResult;

    public SearchForm(Project project, ToolWindow toolWindow) {
        searchResult.setEnabled(true);
        searchResult.setModel(DataCenter.TABLE_MODEL);
        searchText.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode != 10) return;
                DataProcessor.search(getSearchText().getText());
            }
        });


        searchText.getDocument().addDocumentListener(new DocumentAdapter() {
            @Override
            protected void textChanged(@NotNull DocumentEvent documentEvent) {
                try {
                    if (documentEvent.getDocument().getLength() == 0) {
                        DataProcessor.resetSearchResult();
                    }
                    DataProcessor.search(getSearchText().getText());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public JTextField getSearchText() {
        return searchText;
    }

    public JPanel getContentPanel() {
        return contentPanel;
    }

    private void createUIComponents() {
        JTable table = new JTable();
        table.setRowHeight(23);
        table.setEnabled(true);
        table.setModel(DataCenter.TABLE_MODEL);
        Font font = new Font(null,0,10);
        table.setFont(font);
        table.setCellSelectionEnabled(true);
        table.setSelectionMode(0);
        table.setAutoscrolls(true);
        table.setIntercellSpacing(new Dimension(1,1));
        table.setDragEnabled(false);
        searchResult = table;
    }
}
